package top.jybill.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.jybill.domain.*;
import top.jybill.service.IUserService;
import top.jybill.service.Impl.UserServiceImpl;
import top.jybill.utils.JwtUtil;
import top.jybill.utils.Md5Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

  @Autowired
  private ResponseData res;
  @Autowired
  private IUserService userService;

  /**
   * 登陆
   * @param session
   * @param myUser
   * @return
   */
  @RequestMapping(value = "/login", method = RequestMethod.POST)
  @ResponseBody
  public ResponseData login(HttpSession session, @RequestBody MyUser myUser) throws Exception {
    res.clean();
    // 登陆成功返回token - MD5加密
    myUser.setPassword(Md5Util.encodeByMd5(myUser.getPassword()));
    MyUser user = userService.findUser(myUser);
    //System.out.println(user);

    // 判断用户激活
    if (user.getStatus() == 0) {
      res.metaPut("status", 400);
      res.metaPut("msg", "账号未激活");
      return res;
    }

    // 判断是否是被封禁的用户
    for (Role r: user.getRoles()) {
      if ("BAN".equalsIgnoreCase(r.getRoleName())) {
        res.metaPut("status", 400);
        res.metaPut("msg", "账号被封禁");
        return res;
      }
    }

    Map<String, Object> map = new HashMap<>();
    map.put("userInfo", user);
    map.put("roles", user.getRoles());
    map.put("status", user.getStatus());
    HashMap<String, String> permissionMaps = new HashMap<>();
    for (Role r: user.getRoles()) {
      for (Permission p: r.getPermissions()) {
        permissionMaps.put(p.getUrl(), p.getPermissionName());
      }
    }
    map.put("permissions", permissionMaps);

    try {
      String backToken = JwtUtil.TOKEN_PREFIX + JwtUtil.generate(map);
      res.dataPut("token", backToken);
      // 可以存入redis 这里方便存入全局对象
      session.getServletContext().setAttribute(backToken, user);
    } catch (Exception e) {
      e.printStackTrace();
      res.metaPut("status", 500);
      res.metaPut("msg", e.getMessage());
      return res;
    }
    // 序列化并返回token
    res.metaPut("status", 200);
    res.metaPut("msg", "登陆成功");
    return res;
  }

  /**
   * 退出
   * @param request
   * @return
   */
  @RequestMapping("/quite")
  @ResponseBody
  public ResponseData quite(HttpServletRequest request) {
    res.clean();
    request.getSession().getServletContext().removeAttribute(request.getHeader("Authorization"));
    res.metaPut("status", 200);
    res.metaPut("msg", "ok");
    res.dataPut("redirect", "login");
    return res;
  }

  @RequestMapping("/findUsersByPage")
  @ResponseBody
  public ResponseData findUsersByPage(MyPageInfo page) throws Exception {
    res.clean();

    MyPageInfo retPageInfo = userService.findUsersByPage(page);
    res.metaPut("status", 200);
    res.metaPut("msg", "OK");
    res.dataPut("page", retPageInfo);

    return res;
  }

  @RequestMapping("/addUser")
  @ResponseBody
  public ResponseData addUser(@RequestBody MyUser user) throws Exception {
    res.clean();
    userService.addUser(user);
    res.metaPut("status", 200);
    res.metaPut("msg", "OK");
    return res;
  }

  /**
   * 根据用户id删除用户及其关联的role
   * @param uid
   * @return
   */
  @RequestMapping(value = "/delUser/{uid}", method = RequestMethod.DELETE)
  @ResponseBody
  public ResponseData delUser(@PathVariable("uid") String uid) {
    res.clean();
    userService.delUser(uid);
    res.metaPut("status", 200);
    res.metaPut("msg", "OK");
    return res;
  }

  /**
   * 更新用户
   * @param user
   * @return
   */
  @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
  @ResponseBody
  public ResponseData updateUser(@RequestBody MyUser user) throws Exception {
    res.clean();
    System.out.println(user);
    userService.updateUser(user);
    res.metaPut("status", 200);
    res.metaPut("msg", "OK");
    return res;
  }

  /**
   * 根据用户id查询用户
   * @param uid
   * @return
   */
  @RequestMapping(value = "/findUserByuid", method = RequestMethod.GET)
  @ResponseBody
  public ResponseData findUserByuid(String uid) {
    res.clean();
    MyUser user = userService.findUserByuid(uid);
    if (user == null) {
      res.metaPut("status", 400);
      res.metaPut("msg", "用户id不正确");
      return res;
    }
    res.metaPut("status", 200);
    res.metaPut("msg", "OK");
    res.dataPut("user", user);
    return res;
  }
}
